import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as json;

import 'package:flutter_demo/utils/LogUtil.dart';

class HttpDemo extends StatefulWidget {
  const HttpDemo({super.key});

  @override
  State<HttpDemo> createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HttpDemo'),
        elevation: 0.0,
      ),
      body: HttpDemoHome(),
    );
  }
}

class HttpDemoHome extends StatefulWidget {
  const HttpDemoHome({super.key});

  @override
  State<HttpDemoHome> createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {
  @override
  void initState() {
    super.initState();
    fetchPost().then((value) => print(value));
  }

  Future<List<Post>> fetchPost() async {
    var url =
        Uri.https('resources.ninghao.net', '/demo/posts.json', {'q': '{http}'});
    final response = await http.get(url);
    LogUtil.d(
        title: "request",
        'url: ${response.request!.url.path} \n header: ${response.headers.toString()} \n statusCode: ${response.statusCode}  \n body: ${response.body}');

    if (response.statusCode == 200) {
      var jsonResponse = json.jsonDecode(response.body) as Map<String, dynamic>;
      var posts = jsonResponse['posts'];
      var item = posts[0];
      print('item[0]: ${item['title']}');
      var post = Post.fromJson(item);
      print('item[0].title: ${post.title}');

      List<Post> postList =
          posts.map<Post>((item) => Post.fromJson(item)).toList();

      return postList;
    } else {
      throw Exception('Failed to fetch posts');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchPost(),
      builder: (BuildContext builder, AsyncSnapshot snapshot) {
        print('data: ${snapshot.data}');
        print('connectionState: ${snapshot.connectionState}');
        
        if (snapshot.connectionState == ConnectionState.waiting){
          return Center(
            child: Text('loading...'),
          );
        }

        return ListView(
          children: snapshot.data.map<Widget>((Post item){
            return ListTile(
              title: Text(item.title),
              subtitle: Text(item.author),
              leading: CircleAvatar(
                backgroundImage: NetworkImage(item.imageUrl),
              ),
            );
          }).toList(),
        );

      });
  }
}

class Post {
  final int id;
  final String title;
  final String description;
  final String author;
  final String imageUrl;

  Post(this.id, this.title, this.description, this.author, this.imageUrl);

  Post.fromJson(Map json)
      : id = json['id'],
        title = json['title'],
        description = json['description'],
        author = json['author'],
        imageUrl = json['imageUrl'];

  Map toJson() => {
        'id': id,
        'title': title,
        'description': description,
        'author': author,
        'imageUrl': imageUrl
      };
}
